package com.course.design.socketio;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.course.design.entity.Ltxx;
import com.course.design.entity.vo.MessageHisVO;
import com.course.design.entity.vo.UserLoginVO;
import com.course.design.service.LtxxService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述:
 *
 * @author qinlianji
 * @create 2020-02-18
 */
@Component
public class MessageEventHandler {

    private final SocketIOServer server;

    private Logger logger = LoggerFactory.getLogger(MessageEventHandler.class);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    /**
     * 保存所有的 userId ：socket 连接
     */
    private static Map<String, SocketIOClient> userId_socket_Map = new ConcurrentHashMap<>();

    @Autowired
    private LtxxService ltxxService;

    @Autowired
    public MessageEventHandler(SocketIOServer server) {
        this.server = server;
    }

    /**
     * 添加connect事件，当客户端发起连接时调用
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        logger.info("有机器连接，但是未登陆");
    }

    /**
     * 添加@OnDisconnect事件，客户端断开连接时调用，刷新客户端信息
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String obj = (String) client.get("account");
        if (obj != null && userId_socket_Map.get(obj) != null){
            userId_socket_Map.remove(obj);
            logger.info(obj + "--------->下 线了 " + sdf.format(new Date()));
        }else {
            logger.info("有一台未登录机器---->下 线了 ");
        }
        client.disconnect();
    }

    /**
     * 消息接收入口，当接收到消息后，查找发送目标客户端，并且向该客户端发送消息
     * @param client
     * @param request
     * @param data
     */
    @OnEvent(value = "chat")
    public void chat(SocketIOClient client, AckRequest request, Ltxx data){
        ltxxService.save(data);
        String toUser = data.getToUser();
        SocketIOClient socketIOClient = userId_socket_Map.get(toUser);
        if (!ObjectUtils.isEmpty(socketIOClient)){
            socketIOClient.sendEvent("clientChat", data);
        }else {
//            client.sendEvent("offline", "发送对象未在线！");
            logger.info("发送对象未在线！");
        }
    }

    /**
     * 传送文件
     * @param client
     * @param request
     * @param data
     */
    @OnEvent(value = "getFile")
    public void getFile(SocketIOClient client, AckRequest request, Ltxx data){
        String toUser = data.getToUser();
        SocketIOClient socketIOClient = userId_socket_Map.get(toUser);
        if (!ObjectUtils.isEmpty(socketIOClient)){
            socketIOClient.sendEvent("getFile", data.getWjxxbsId());
        }else {
            client.sendEvent("offline", "发送对象未在线！");
        }
    }

    @OnEvent(value = "login")
    public void login(SocketIOClient client, AckRequest ackRequest, UserLoginVO vo){
        String account = vo.getAccount();
        String username = vo.getUsername();
        client.set("account", account);
        client.set("username", username);
        userId_socket_Map.put(account, client);
        logger.info(username + "------> 上线了" + sdf.format(new Date()));
        client.sendEvent("login", username + "---> 上线了");
    }
}
